<?php

namespace App\HttpController;


use EasySwoole\EasySwoole\Config;
use EasySwoole\Redis\Redis;
use EasySwoole\RedisPool\RedisPool;
use Trois\Lib\Help;

class JavaBase extends Base
{

    protected array $loginUser = [];

    protected string $userJavaTokenKeyPre = 'userJavaToken:';

    protected string $javaTokenError = '';

    public function onRequest(?string $action): ?bool
    {
        $token = $this->request()->getHeader('token')[0] ?? '';

        if (!$token) {
            $this->writeJson(400, null, '请先登录');
            return false;
        }

        // 优先REDIS
        $isOk = $this->verifyToken($token);

        if (!$isOk) {

            // 从Java获取
            if (!$this->getJavaToken($token)) {
                $this->writeJson(400, null, $this->javaTokenError);
                return false;
            }

            return false;

        }

        return true;
    }


    protected function verifyToken(string $token): bool
    {

        $user = RedisPool::invoke(function (Redis $redis) use ($token) {

            $user = $redis->get($this->userJavaTokenKeyPre . $token);

            return $user ? json_decode($user, true) : [];

        });


        if (!$user || !isset($user['user_id'])) {
            return false;
        }

        $this->loginUser = $user;

        return true;

    }


    protected function getJavaToken(string $token): bool
    {
        $postData = [
            'tokenId' => $token
        ];

        $JAVAApiUrl = Config::getInstance()->getConf('JAVAApiUrl');

        $JAVAApiUrl = $JAVAApiUrl ?: 'https://apis.zhimeibot.com';

        $url = $JAVAApiUrl . '/blade-auth/analysisUserByToken';

        $res = Help::curl('post',
            $url,
            $postData, [], 2);

        if ($res['response_code'] !== 0) {
            $this->javaTokenError = $res['response_msg'];
            return false;
        }

        $response_content = $res['response_content'];

        if ($response_content['code'] !== 1) {
            $this->javaTokenError = 'code:' . $response_content['code'] . ', msg:' . $response_content['msg'];
            return false;
        }

        $user = $response_content['data'];

        if (!$user || !isset($user['user_id'])) {
            $this->javaTokenError = '身份已过期，请重新登陆';
            return false;
        }

        $this->setUserToken($token, $user);

        $this->loginUser = $user;

        return true;

    }

    protected function setUserToken(string $token, array $user): void
    {

        RedisPool::invoke(function (Redis $redis) use ($token, $user) {
            $redis->set($this->userJavaTokenKeyPre . $token, json_encode($user, JSON_UNESCAPED_UNICODE), 86400 * 2);
        });

    }

    protected function getValidate(string $actionName): array
    {
        return [];
    }

    protected function initService(array $postParams, array $loginUser): void
    {
        // TODO: Implement initService() method.
    }
}